<template>
  <div class="doctor-record-full">
    <h1 class="text-2xl font-bold mb-6 text-blue-800">创建病历</h1>
    
    <div class="bg-white shadow-md rounded-lg p-6 mb-6">
      <h2 class="text-lg font-semibold mb-5 text-gray-700 border-b border-gray-200 pb-2">患者信息</h2>
      <form @submit.prevent="submitMedicalRecord">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <label class="block text-sm font-medium text-gray-600">患者姓名</label>
            <input v-model="form.patientName" type="text" 
                   :class="{'border-red-500': errors.patientName}"
                   class="mt-2 block w-full border border-gray-300 rounded-lg p-3 focus:ring-2 focus:ring-blue-500 focus:border-transparent" 
                   @blur="validateField('patientName')"
                   required>
            <p v-if="errors.patientName" class="text-red-500 text-xs mt-1">{{ errors.patientName }}</p>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-600">诊断结果</label>
            <textarea v-model="form.diagnosis" 
                      :class="{'border-red-500': errors.diagnosis}"
                      class="mt-2 block w-full border border-gray-300 rounded-lg p-3 focus:ring-2 focus:ring-blue-500 focus:border-transparent" 
                      rows="4" 
                      @blur="validateField('diagnosis')"
                      required></textarea>
            <p v-if="errors.diagnosis" class="text-red-500 text-xs mt-1">{{ errors.diagnosis }}</p>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-600">处方</label>
            <textarea v-model="form.prescription" 
                      :class="{'border-red-500': errors.prescription}"
                      class="mt-2 block w-full border border-gray-300 rounded-lg p-3 focus:ring-2 focus:ring-blue-500 focus:border-transparent" 
                      rows="4"
                      @blur="validateField('prescription')"></textarea>
            <p v-if="errors.prescription" class="text-red-500 text-xs mt-1">{{ errors.prescription }}</p>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-600">过敏史</label>
            <textarea v-model="form.allergyHistory" 
                      :class="{'border-red-500': errors.allergyHistory}"
                      class="mt-2 block w-full border border-gray-300 rounded-lg p-3 focus:ring-2 focus:ring-blue-500 focus:border-transparent" 
                      rows="4"
                      @blur="validateField('allergyHistory')"></textarea>
            <p v-if="errors.allergyHistory" class="text-red-500 text-xs mt-1">{{ errors.allergyHistory }}</p>
          </div>
        </div>
        <button type="submit" class="mt-6 bg-blue-600 text-white px-5 py-2.5 rounded-lg hover:bg-blue-700 transition duration-300">保存病历</button>
      </form>
    </div>

    <div class="bg-white shadow-md rounded-lg p-6 mb-6">
      <h2 class="text-lg font-semibold mb-5 text-gray-700 border-b border-gray-200 pb-2">上传检查报告/X光片</h2>
      <input type="file" multiple @change="handleFileUpload" accept="image/*,application/pdf" 
             class="mt-2 mb-4 w-full border border-gray-300 rounded-lg p-3 focus:ring-2 focus:ring-blue-500 focus:border-transparent">
      <p v-if="errors.files" class="text-red-500 text-xs mt-1 mb-2">{{ errors.files }}</p>
      <div v-if="uploadedFiles.length" class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div v-for="(file, index) in uploadedFiles" :key="index" class="border border-gray-200 rounded-lg p-4 bg-gray-50 hover:bg-gray-100 transition">
          <img v-if="file.type.startsWith('image/')" :src="file.url" class="w-full h-32 object-cover rounded-lg mb-2">
          <p v-else class="text-gray-700 text-sm">{{ file.name }}</p>
          <button @click="removeFile(index)" class="text-red-500 hover:text-red-700 mt-2 text-sm">删除</button>
        </div>
      </div>
    </div>

    <!-- 成功弹窗 - 中央跳出效果 -->
    <transition name="popup">
      <div v-if="showSuccessModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
        <div class="modal-content bg-white rounded-lg p-8 w-[410px] max-w-[90vw] shadow-2xl border border-gray-200">
          <div class="text-center">
            <h3 class="text-2xl font-bold text-gray-800 mb-4">创建成功</h3>
            <p class="text-gray-600 mb-8 text-lg">病历已成功保存到系统</p>
            
            <button 
              @click="showSuccessModal = false" 
              class="bg-blue-600 text-white px-8 py-3 rounded-lg hover:bg-blue-700 transition-all duration-200 text-base font-medium shadow-md hover:shadow-lg"
            >
              确定
            </button>
          </div>
        </div>
      </div>
    </transition>

    <!-- 错误提示弹窗 - 中央跳出效果 -->
    <transition name="popup">
      <div v-if="showErrorModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
        <div class="modal-content bg-white rounded-lg p-8 w-[410px] max-w-[90vw] shadow-2xl border border-gray-200">
          <div class="text-center">
            <h3 class="text-2xl font-bold text-gray-800 mb-4">操作失败</h3>
            <p class="text-gray-600 mb-8 text-lg">{{ errorMessage }}</p>
            
            <button 
              @click="showErrorModal = false" 
              class="bg-red-600 text-white px-8 py-3 rounded-lg hover:bg-red-700 transition-all duration-200 text-base font-medium shadow-md hover:shadow-lg"
            >
              重试
            </button>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      form: {
        patientName: '',
        diagnosis: '',
        prescription: '',
        allergyHistory: ''
      },
      uploadedFiles: [],
      errors: {
        patientName: '',
        diagnosis: '',
        prescription: '',
        allergyHistory: '',
        files: ''
      },
      validationRules: {
        patientName: {
          required: true,
          minLength: 2,
          maxLength: 50,
          pattern: /^[\u4e00-\u9fa5a-zA-Z\s]+$/
        },
        diagnosis: {
          required: true,
          minLength: 5,
          maxLength: 1000
        },
        prescription: {
          required: false,
          maxLength: 1000
        },
        allergyHistory: {
          required: false,
          maxLength: 500
        }
      },
      showSuccessModal: false,
      showErrorModal: false,
      errorMessage: ''
    };
  },
  computed: {
    isFormValid() {
      return !this.errors.patientName && 
             !this.errors.diagnosis && 
             !this.errors.prescription && 
             !this.errors.allergyHistory &&
             this.form.patientName && 
             this.form.diagnosis;
    }
  },
  methods: {
    validateField(fieldName) {
      const value = this.form[fieldName];
      const rules = this.validationRules[fieldName];
      this.errors[fieldName] = '';

      if (rules.required && !value) {
        this.errors[fieldName] = '此字段为必填项';
        return false;
      }

      if (value && rules.minLength && value.length < rules.minLength) {
        this.errors[fieldName] = `至少需要 ${rules.minLength} 个字符`;
        return false;
      }

      if (value && rules.maxLength && value.length > rules.maxLength) {
        this.errors[fieldName] = `不能超过 ${rules.maxLength} 个字符`;
        return false;
      }

      if (value && rules.pattern && !rules.pattern.test(value)) {
        this.errors[fieldName] = '格式不正确，请使用有效字符';
        return false;
      }

      return true;
    },
    validateFiles() {
      this.errors.files = '';
      
      if (this.uploadedFiles.length === 0) {
        return true;
      }
      
      const maxSize = 5 * 1024 * 1024;
      for (const file of this.uploadedFiles) {
        if (file.file.size > maxSize) {
          this.errors.files = `文件 "${file.name}" 大小不能超过5MB`;
          return false;
        }
      }
      
      return true;
    },
    validateForm() {
      let isValid = true;
      
      Object.keys(this.validationRules).forEach(field => {
        if (!this.validateField(field)) {
          isValid = false;
        }
      });
      
      if (!this.validateFiles()) {
        isValid = false;
      }
      
      return isValid;
    },
    handleFileUpload(event) {
      const files = Array.from(event.target.files);
      this.uploadedFiles = files.map(file => ({
        name: file.name,
        type: file.type,
        url: file.type.startsWith('image/') ? URL.createObjectURL(file) : null,
        file
      }));
      
      this.validateFiles();
    },
    removeFile(index) {
      this.uploadedFiles.splice(index, 1);
      this.validateFiles();
    },
    showError(message) {
      this.errorMessage = message;
      this.showErrorModal = true;
      
      // 5秒后自动关闭错误弹窗
      setTimeout(() => {
        this.showErrorModal = false;
      }, 5000);
    },
    async submitMedicalRecord() {
      if (!this.validateForm()) {
        this.showError('请检查表单中的错误');
        return;
      }
      
      try {
        // 模拟API调用
        console.log('提交病历数据:', this.form);
        
        // 模拟网络延迟
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        // 显示成功弹窗
        this.showSuccessModal = true;
        
        // 3秒后自动关闭成功弹窗
        setTimeout(() => {
          this.showSuccessModal = false;
        }, 3000);
        
      } catch (error) {
        this.showError('保存失败，请重试！');
      }
    }
  }
};
</script>

<style scoped>
/* 基础布局 */
.doctor-record-full {
  max-width: 900px;
  margin: 0 auto;
  padding: 2rem 1.5rem;
  background-color: #f9fafb;
  min-height: calc(100vh - 4rem);
}

/* 标题样式 */
h1 {
  color: #2a3660;
  font-size: 1.75rem;
  font-weight: 600;
  margin-bottom: 2rem;
  padding-bottom: 0.75rem;
  border-bottom: 1px solid #e5e7eb;
}

h2 {
  color: #374151;
  font-size: 1.25rem;
  font-weight: 500;
  margin-bottom: 1.5rem;
}

/* 卡片容器 */
.bg-white {
  background-color: white;
  border-radius: 0.75rem;
  padding: 1.5rem;
  margin-bottom: 1.5rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  border: 1px solid #e5e7eb;
}

/* 表单元素 */
input[type="text"],
textarea,
input[type="file"] {
  width: 100%;
  border: 1px solid #d1d5db;
  border-radius: 0.5rem;
  padding: 0.75rem;
  font-size: 0.9375rem;
  background-color: #f9fafb;
  transition: all 0.15s ease;
}

input[type="text"]:focus,
textarea:focus,
input[type="file"]:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
  background-color: white;
}

textarea {
  min-height: 120px;
  resize: vertical;
}

/* 错误状态 */
.border-red-500 {
  border-color: #ef4444;
}

.text-red-500 {
  color: #ef4444;
  font-size: 0.8125rem;
  margin-top: 0.25rem;
}

/* 按钮样式 */
button[type="submit"] {
  background-color: #213452;
  color: white;
  font-weight: 500;
  padding: 0.75rem 1.5rem;
  border-radius: 0.5rem;
  transition: all 0.15s ease;
  border: none;
  font-size: 0.9375rem;
}

button[type="submit"]:hover {
  background-color: #2563eb;
}

button[type="submit"]:active {
  transform: scale(0.98);
}

/* 文件上传区域 */
.uploaded-files-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 1rem;
  margin-top: 1rem;
}

.uploaded-file {
  border: 1px solid #e5e7eb;
  border-radius: 0.5rem;
  padding: 1rem;
  background-color: #f9fafb;
  transition: all 0.15s ease;
}

.uploaded-file:hover {
  border-color: #d1d5db;
}

.remove-file-btn {
  color: #ef4444;
  font-size: 0.8125rem;
  margin-top: 0.5rem;
  display: inline-block;
}

.remove-file-btn:hover {
  text-decoration: underline;
}

/* 弹窗样式 */
.modal-overlay {
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  background-color: white;
  border-radius: 0.75rem;
  padding: 2rem;
  max-width: 400px;
  width: 90%;
  margin: 0 auto;
}

.modal-title {
  font-size: 1.25rem;
  font-weight: 600;
  margin-bottom: 1rem;
  color: #1f2937;
}

.modal-message {
  color: #4b5563;
  margin-bottom: 1.5rem;
}

.modal-button {
  padding: 0.625rem 1.25rem;
  border-radius: 0.5rem;
  font-weight: 500;
}

/* 动画效果 */
.popup-enter-active,
.popup-leave-active {
  transition: opacity 0.2s ease;
}

.popup-enter-from,
.popup-leave-to {
  opacity: 0;
}

.popup-enter-active .modal-content,
.popup-leave-active .modal-content {
  transition: all 0.2s ease;
}

.popup-enter-from .modal-content,
.popup-leave-to .modal-content {
  opacity: 0;
  transform: translateY(-10px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .doctor-record-full {
    padding: 1.5rem 1rem;
  }
  
  .grid-cols-2 {
    grid-template-columns: 1fr;
  }
  
  h1 {
    font-size: 1.5rem;
  }
  
  .uploaded-files-container {
    grid-template-columns: 1fr;
  }
}
</style>